home *** CD-ROM | disk | FTP | other *** search
/ Clickx 96 / Clickx 96.iso / software / tools / tool / xbmc-10.1.exe / addons / script.module.pil / lib / PIL / Image.py < prev    next >
Encoding:
Python Source  |  2009-11-15  |  65.7 KB  |  2,128 lines

  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # the Image class wrapper
  6. #
  7. # partial release history:
  8. # 1995-09-09 fl   Created
  9. # 1996-03-11 fl   PIL release 0.0 (proof of concept)
  10. # 1996-04-30 fl   PIL release 0.1b1
  11. # 1999-07-28 fl   PIL release 1.0 final
  12. # 2000-06-07 fl   PIL release 1.1
  13. # 2000-10-20 fl   PIL release 1.1.1
  14. # 2001-05-07 fl   PIL release 1.1.2
  15. # 2002-03-15 fl   PIL release 1.1.3
  16. # 2003-05-10 fl   PIL release 1.1.4
  17. # 2005-03-28 fl   PIL release 1.1.5
  18. # 2006-12-02 fl   PIL release 1.1.6
  19. # 2009-11-15 fl   PIL release 1.1.7
  20. #
  21. # Copyright (c) 1997-2009 by Secret Labs AB.  All rights reserved.
  22. # Copyright (c) 1995-2009 by Fredrik Lundh.
  23. #
  24. # See the README file for information on usage and redistribution.
  25. #
  26.  
  27. VERSION = "1.1.7"
  28.  
  29. try:
  30.     import warnings
  31. except ImportError:
  32.     warnings = None
  33.  
  34. class _imaging_not_installed:
  35.     # module placeholder
  36.     def __getattr__(self, id):
  37.         raise ImportError("The _imaging C module is not installed")
  38.  
  39. try:
  40.     # give Tk a chance to set up the environment, in case we're
  41.     # using an _imaging module linked against libtcl/libtk (use
  42.     # __import__ to hide this from naive packagers; we don't really
  43.     # depend on Tk unless ImageTk is used, and that module already
  44.     # imports Tkinter)
  45.     __import__("FixTk")
  46. except ImportError:
  47.     pass
  48.  
  49. try:
  50.     # If the _imaging C module is not present, you can still use
  51.     # the "open" function to identify files, but you cannot load
  52.     # them.  Note that other modules should not refer to _imaging
  53.     # directly; import Image and use the Image.core variable instead.
  54.     import _imaging
  55.     core = _imaging
  56.     del _imaging
  57. except ImportError, v:
  58.     core = _imaging_not_installed()
  59.     if str(v)[:20] == "Module use of python" and warnings:
  60.         # The _imaging C module is present, but not compiled for
  61.         # the right version (windows only).  Print a warning, if
  62.         # possible.
  63.         warnings.warn(
  64.             "The _imaging extension was built for another version "
  65.             "of Python; most PIL functions will be disabled",
  66.             RuntimeWarning
  67.             )
  68.  
  69. import ImageMode
  70. import ImagePalette
  71.  
  72. import os, string, sys
  73.  
  74. # type stuff
  75. from types import IntType, StringType, TupleType
  76.  
  77. try:
  78.     UnicodeStringType = type(unicode(""))
  79.     ##
  80.     # (Internal) Checks if an object is a string.  If the current
  81.     # Python version supports Unicode, this checks for both 8-bit
  82.     # and Unicode strings.
  83.     def isStringType(t):
  84.         return isinstance(t, StringType) or isinstance(t, UnicodeStringType)
  85. except NameError:
  86.     def isStringType(t):
  87.         return isinstance(t, StringType)
  88.  
  89. ##
  90. # (Internal) Checks if an object is a tuple.
  91.  
  92. def isTupleType(t):
  93.     return isinstance(t, TupleType)
  94.  
  95. ##
  96. # (Internal) Checks if an object is an image object.
  97.  
  98. def isImageType(t):
  99.     return hasattr(t, "im")
  100.  
  101. ##
  102. # (Internal) Checks if an object is a string, and that it points to a
  103. # directory.
  104.  
  105. def isDirectory(f):
  106.     return isStringType(f) and os.path.isdir(f)
  107.  
  108. from operator import isNumberType, isSequenceType
  109.  
  110. #
  111. # Debug level
  112.  
  113. DEBUG = 0
  114.  
  115. #
  116. # Constants (also defined in _imagingmodule.c!)
  117.  
  118. NONE = 0
  119.  
  120. # transpose
  121. FLIP_LEFT_RIGHT = 0
  122. FLIP_TOP_BOTTOM = 1
  123. ROTATE_90 = 2
  124. ROTATE_180 = 3
  125. ROTATE_270 = 4
  126.  
  127. # transforms
  128. AFFINE = 0
  129. EXTENT = 1
  130. PERSPECTIVE = 2
  131. QUAD = 3
  132. MESH = 4
  133.  
  134. # resampling filters
  135. NONE = 0
  136. NEAREST = 0
  137. ANTIALIAS = 1 # 3-lobed lanczos
  138. LINEAR = BILINEAR = 2
  139. CUBIC = BICUBIC = 3
  140.  
  141. # dithers
  142. NONE = 0
  143. NEAREST = 0
  144. ORDERED = 1 # Not yet implemented
  145. RASTERIZE = 2 # Not yet implemented
  146. FLOYDSTEINBERG = 3 # default
  147.  
  148. # palettes/quantizers
  149. WEB = 0
  150. ADAPTIVE = 1
  151.  
  152. # categories
  153. NORMAL = 0
  154. SEQUENCE = 1
  155. CONTAINER = 2
  156.  
  157. # --------------------------------------------------------------------
  158. # Registries
  159.  
  160. ID = []
  161. OPEN = {}
  162. MIME = {}
  163. SAVE = {}
  164. EXTENSION = {}
  165.  
  166. # --------------------------------------------------------------------
  167. # Modes supported by this version
  168.  
  169. _MODEINFO = {
  170.     # NOTE: this table will be removed in future versions.  use
  171.     # getmode* functions or ImageMode descriptors instead.
  172.  
  173.     # official modes
  174.     "1": ("L", "L", ("1",)),
  175.     "L": ("L", "L", ("L",)),
  176.     "I": ("L", "I", ("I",)),
  177.     "F": ("L", "F", ("F",)),
  178.     "P": ("RGB", "L", ("P",)),
  179.     "RGB": ("RGB", "L", ("R", "G", "B")),
  180.     "RGBX": ("RGB", "L", ("R", "G", "B", "X")),
  181.     "RGBA": ("RGB", "L", ("R", "G", "B", "A")),
  182.     "CMYK": ("RGB", "L", ("C", "M", "Y", "K")),
  183.     "YCbCr": ("RGB", "L", ("Y", "Cb", "Cr")),
  184.  
  185.     # Experimental modes include I;16, I;16L, I;16B, RGBa, BGR;15, and
  186.     # BGR;24.  Use these modes only if you know exactly what you're
  187.     # doing...
  188.  
  189. }
  190.  
  191. try:
  192.     byteorder = sys.byteorder
  193. except AttributeError:
  194.     import struct
  195.     if struct.unpack("h", "\0\1")[0] == 1:
  196.         byteorder = "big"
  197.     else:
  198.         byteorder = "little"
  199.  
  200. if byteorder == 'little':
  201.     _ENDIAN = '<'
  202. else:
  203.     _ENDIAN = '>'
  204.  
  205. _MODE_CONV = {
  206.     # official modes
  207.     "1": ('|b1', None), # broken
  208.     "L": ('|u1', None),
  209.     "I": (_ENDIAN + 'i4', None),
  210.     "F": (_ENDIAN + 'f4', None),
  211.     "P": ('|u1', None),
  212.     "RGB": ('|u1', 3),
  213.     "RGBX": ('|u1', 4),
  214.     "RGBA": ('|u1', 4),
  215.     "CMYK": ('|u1', 4),
  216.     "YCbCr": ('|u1', 4),
  217. }
  218.  
  219. def _conv_type_shape(im):
  220.     shape = im.size[1], im.size[0]
  221.     typ, extra = _MODE_CONV[im.mode]
  222.     if extra is None:
  223.         return shape, typ
  224.     else:
  225.         return shape+(extra,), typ
  226.  
  227.  
  228. MODES = _MODEINFO.keys()
  229. MODES.sort()
  230.  
  231. # raw modes that may be memory mapped.  NOTE: if you change this, you
  232. # may have to modify the stride calculation in map.c too!
  233. _MAPMODES = ("L", "P", "RGBX", "RGBA", "CMYK", "I;16", "I;16L", "I;16B")
  234.  
  235. ##
  236. # Gets the "base" mode for given mode.  This function returns "L" for
  237. # images that contain grayscale data, and "RGB" for images that
  238. # contain color data.
  239. #
  240. # @param mode Input mode.
  241. # @return "L" or "RGB".
  242. # @exception KeyError If the input mode was not a standard mode.
  243.  
  244. def getmodebase(mode):
  245.     return ImageMode.getmode(mode).basemode
  246.  
  247. ##
  248. # Gets the storage type mode.  Given a mode, this function returns a
  249. # single-layer mode suitable for storing individual bands.
  250. #
  251. # @param mode Input mode.
  252. # @return "L", "I", or "F".
  253. # @exception KeyError If the input mode was not a standard mode.
  254.  
  255. def getmodetype(mode):
  256.     return ImageMode.getmode(mode).basetype
  257.  
  258. ##
  259. # Gets a list of individual band names.  Given a mode, this function
  260. # returns a tuple containing the names of individual bands (use
  261. # {@link #getmodetype} to get the mode used to store each individual
  262. # band.
  263. #
  264. # @param mode Input mode.
  265. # @return A tuple containing band names.  The length of the tuple
  266. #     gives the number of bands in an image of the given mode.
  267. # @exception KeyError If the input mode was not a standard mode.
  268.  
  269. def getmodebandnames(mode):
  270.     return ImageMode.getmode(mode).bands
  271.  
  272. ##
  273. # Gets the number of individual bands for this mode.
  274. #
  275. # @param mode Input mode.
  276. # @return The number of bands in this mode.
  277. # @exception KeyError If the input mode was not a standard mode.
  278.  
  279. def getmodebands(mode):
  280.     return len(ImageMode.getmode(mode).bands)
  281.  
  282. # --------------------------------------------------------------------
  283. # Helpers
  284.  
  285. _initialized = 0
  286.  
  287. ##
  288. # Explicitly loads standard file format drivers.
  289.  
  290. def preinit():
  291.     "Load standard file format drivers."
  292.  
  293.     global _initialized
  294.     if _initialized >= 1:
  295.         return
  296.  
  297.     try:
  298.         import BmpImagePlugin
  299.     except ImportError:
  300.         pass
  301.     try:
  302.         import GifImagePlugin
  303.     except ImportError:
  304.         pass
  305.     try:
  306.         import JpegImagePlugin
  307.     except ImportError:
  308.         pass
  309.     try:
  310.         import PpmImagePlugin
  311.     except ImportError:
  312.         pass
  313.     try:
  314.         import PngImagePlugin
  315.     except ImportError:
  316.         pass
  317. #   try:
  318. #       import TiffImagePlugin
  319. #   except ImportError:
  320. #       pass
  321.  
  322.     _initialized = 1
  323.  
  324. ##
  325. # Explicitly initializes the Python Imaging Library.  This function
  326. # loads all available file format drivers.
  327.  
  328. def init():
  329.     "Load all file format drivers."
  330.  
  331.     global _initialized
  332.     if _initialized >= 2:
  333.         return 0
  334.  
  335.     visited = {}
  336.  
  337.     directories = sys.path
  338.  
  339.     try:
  340.         directories = directories + [os.path.dirname(__file__)]
  341.     except NameError:
  342.         pass
  343.  
  344.     # only check directories (including current, if present in the path)
  345.     for directory in filter(isDirectory, directories):
  346.         fullpath = os.path.abspath(directory)
  347.         if visited.has_key(fullpath):
  348.             continue
  349.         for file in os.listdir(directory):
  350.             if file[-14:] == "ImagePlugin.py":
  351.                 f, e = os.path.splitext(file)
  352.                 try:
  353.                     sys.path.insert(0, directory)
  354.                     try:
  355.                         __import__(f, globals(), locals(), [])
  356.                     finally:
  357.                         del sys.path[0]
  358.                 except ImportError:
  359.                     if DEBUG:
  360.                         print "Image: failed to import",
  361.                         print f, ":", sys.exc_value
  362.         visited[fullpath] = None
  363.  
  364.     if OPEN or SAVE:
  365.         _initialized = 2
  366.         return 1
  367.  
  368. # --------------------------------------------------------------------
  369. # Codec factories (used by tostring/fromstring and ImageFile.load)
  370.  
  371. def _getdecoder(mode, decoder_name, args, extra=()):
  372.  
  373.     # tweak arguments
  374.     if args is None:
  375.         args = ()
  376.     elif not isTupleType(args):
  377.         args = (args,)
  378.  
  379.     try:
  380.         # get decoder
  381.         decoder = getattr(core, decoder_name + "_decoder")
  382.         # print decoder, (mode,) + args + extra
  383.         return apply(decoder, (mode,) + args + extra)
  384.     except AttributeError:
  385.         raise IOError("decoder %s not available" % decoder_name)
  386.  
  387. def _getencoder(mode, encoder_name, args, extra=()):
  388.  
  389.     # tweak arguments
  390.     if args is None:
  391.         args = ()
  392.     elif not isTupleType(args):
  393.         args = (args,)
  394.  
  395.     try:
  396.         # get encoder
  397.         encoder = getattr(core, encoder_name + "_encoder")
  398.         # print encoder, (mode,) + args + extra
  399.         return apply(encoder, (mode,) + args + extra)
  400.     except AttributeError:
  401.         raise IOError("encoder %s not available" % encoder_name)
  402.  
  403.  
  404. # --------------------------------------------------------------------
  405. # Simple expression analyzer
  406.  
  407. class _E:
  408.     def __init__(self, data): self.data = data
  409.     def __coerce__(self, other): return self, _E(other)
  410.     def __add__(self, other): return _E((self.data, "__add__", other.data))
  411.     def __mul__(self, other): return _E((self.data, "__mul__", other.data))
  412.  
  413. def _getscaleoffset(expr):
  414.     stub = ["stub"]
  415.     data = expr(_E(stub)).data
  416.     try:
  417.         (a, b, c) = data # simplified syntax
  418.         if (a is stub and b == "__mul__" and isNumberType(c)):
  419.             return c, 0.0
  420.         if (a is stub and b == "__add__" and isNumberType(c)):
  421.             return 1.0, c
  422.     except TypeError: pass
  423.     try:
  424.         ((a, b, c), d, e) = data # full syntax
  425.         if (a is stub and b == "__mul__" and isNumberType(c) and
  426.             d == "__add__" and isNumberType(e)):
  427.             return c, e
  428.     except TypeError: pass
  429.     raise ValueError("illegal expression")
  430.  
  431.  
  432. # --------------------------------------------------------------------
  433. # Implementation wrapper
  434.  
  435. ##
  436. # This class represents an image object.  To create Image objects, use
  437. # the appropriate factory functions.  There's hardly ever any reason
  438. # to call the Image constructor directly.
  439. #
  440. # @see #open
  441. # @see #new
  442. # @see #fromstring
  443.  
  444. class Image:
  445.  
  446.     format = None
  447.     format_description = None
  448.  
  449.     def __init__(self):
  450.         # FIXME: take "new" parameters / other image?
  451.         # FIXME: turn mode and size into delegating properties?
  452.         self.im = None
  453.         self.mode = ""
  454.         self.size = (0, 0)
  455.         self.palette = None
  456.         self.info = {}
  457.         self.category = NORMAL
  458.         self.readonly = 0
  459.  
  460.     def _new(self, im):
  461.         new = Image()
  462.         new.im = im
  463.         new.mode = im.mode
  464.         new.size = im.size
  465.         new.palette = self.palette
  466.         if im.mode == "P":
  467.             new.palette = ImagePalette.ImagePalette()
  468.         try:
  469.             new.info = self.info.copy()
  470.         except AttributeError:
  471.             # fallback (pre-1.5.2)
  472.             new.info = {}
  473.             for k, v in self.info:
  474.                 new.info[k] = v
  475.         return new
  476.  
  477.     _makeself = _new # compatibility
  478.  
  479.     def _copy(self):
  480.         self.load()
  481.         self.im = self.im.copy()
  482.         self.readonly = 0
  483.  
  484.     def _dump(self, file=None, format=None):
  485.         import tempfile
  486.         if not file:
  487.             file = tempfile.mktemp()
  488.         self.load()
  489.         if not format or format == "PPM":
  490.             self.im.save_ppm(file)
  491.         else:
  492.             file = file + "." + format
  493.             self.save(file, format)
  494.         return file
  495.  
  496.     def __repr__(self):
  497.         return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % (
  498.             self.__class__.__module__, self.__class__.__name__,
  499.             self.mode, self.size[0], self.size[1],
  500.             id(self)
  501.             )
  502.  
  503.     def __getattr__(self, name):
  504.         if name == "__array_interface__":
  505.             # numpy array interface support
  506.             new = {}
  507.             shape, typestr = _conv_type_shape(self)
  508.             new['shape'] = shape
  509.             new['typestr'] = typestr
  510.             new['data'] = self.tostring()
  511.             return new
  512.         raise AttributeError(name)
  513.  
  514.     ##
  515.     # Returns a string containing pixel data.
  516.     #
  517.     # @param encoder_name What encoder to use.  The default is to
  518.     #    use the standard "raw" encoder.
  519.     # @param *args Extra arguments to the encoder.
  520.     # @return An 8-bit string.
  521.  
  522.     def tostring(self, encoder_name="raw", *args):
  523.         "Return image as a binary string"
  524.  
  525.         # may pass tuple instead of argument list
  526.         if len(args) == 1 and isTupleType(args[0]):
  527.             args = args[0]
  528.  
  529.         if encoder_name == "raw" and args == ():
  530.             args = self.mode
  531.  
  532.         self.load()
  533.  
  534.         # unpack data
  535.         e = _getencoder(self.mode, encoder_name, args)
  536.         e.setimage(self.im)
  537.  
  538.         bufsize = max(65536, self.size[0] * 4) # see RawEncode.c
  539.  
  540.         data = []
  541.         while 1:
  542.             l, s, d = e.encode(bufsize)
  543.             data.append(d)
  544.             if s:
  545.                 break
  546.         if s < 0:
  547.             raise RuntimeError("encoder error %d in tostring" % s)
  548.  
  549.         return string.join(data, "")
  550.  
  551.     ##
  552.     # Returns the image converted to an X11 bitmap.  This method
  553.     # only works for mode "1" images.
  554.     #
  555.     # @param name The name prefix to use for the bitmap variables.
  556.     # @return A string containing an X11 bitmap.
  557.     # @exception ValueError If the mode is not "1"
  558.  
  559.     def tobitmap(self, name="image"):
  560.         "Return image as an XBM bitmap"
  561.  
  562.         self.load()
  563.         if self.mode != "1":
  564.             raise ValueError("not a bitmap")
  565.         data = self.tostring("xbm")
  566.         return string.join(["#define %s_width %d\n" % (name, self.size[0]),
  567.                 "#define %s_height %d\n"% (name, self.size[1]),
  568.                 "static char %s_bits[] = {\n" % name, data, "};"], "")
  569.  
  570.     ##
  571.     # Loads this image with pixel data from a string.
  572.     # <p>
  573.     # This method is similar to the {@link #fromstring} function, but
  574.     # loads data into this image instead of creating a new image
  575.     # object.
  576.  
  577.     def fromstring(self, data, decoder_name="raw", *args):
  578.         "Load data to image from binary string"
  579.  
  580.         # may pass tuple instead of argument list
  581.         if len(args) == 1 and isTupleType(args[0]):
  582.             args = args[0]
  583.  
  584.         # default format
  585.         if decoder_name == "raw" and args == ():
  586.             args = self.mode
  587.  
  588.         # unpack data
  589.         d = _getdecoder(self.mode, decoder_name, args)
  590.         d.setimage(self.im)
  591.         s = d.decode(data)
  592.  
  593.         if s[0] >= 0:
  594.             raise ValueError("not enough image data")
  595.         if s[1] != 0:
  596.             raise ValueError("cannot decode image data")
  597.  
  598.     ##
  599.     # Allocates storage for the image and loads the pixel data.  In
  600.     # normal cases, you don't need to call this method, since the
  601.     # Image class automatically loads an opened image when it is
  602.     # accessed for the first time.
  603.     #
  604.     # @return An image access object.
  605.  
  606.     def load(self):
  607.         "Explicitly load pixel data."
  608.         if self.im and self.palette and self.palette.dirty:
  609.             # realize palette
  610.             apply(self.im.putpalette, self.palette.getdata())
  611.             self.palette.dirty = 0
  612.             self.palette.mode = "RGB"
  613.             self.palette.rawmode = None
  614.             if self.info.has_key("transparency"):
  615.                 self.im.putpalettealpha(self.info["transparency"], 0)
  616.                 self.palette.mode = "RGBA"
  617.         if self.im:
  618.             return self.im.pixel_access(self.readonly)
  619.  
  620.     ##
  621.     # Verifies the contents of a file. For data read from a file, this
  622.     # method attempts to determine if the file is broken, without
  623.     # actually decoding the image data.  If this method finds any
  624.     # problems, it raises suitable exceptions.  If you need to load
  625.     # the image after using this method, you must reopen the image
  626.     # file.
  627.  
  628.     def verify(self):
  629.         "Verify file contents."
  630.         pass
  631.  
  632.     ##
  633.     # Returns a converted copy of this image. For the "P" mode, this
  634.     # method translates pixels through the palette.  If mode is
  635.     # omitted, a mode is chosen so that all information in the image
  636.     # and the palette can be represented without a palette.
  637.     # <p>
  638.     # The current version supports all possible conversions between
  639.     # "L", "RGB" and "CMYK."
  640.     # <p>
  641.     # When translating a colour image to black and white (mode "L"),
  642.     # the library uses the ITU-R 601-2 luma transform:
  643.     # <p>
  644.     # <b>L = R * 299/1000 + G * 587/1000 + B * 114/1000</b>
  645.     # <p>
  646.     # When translating a greyscale image into a bilevel image (mode
  647.     # "1"), all non-zero values are set to 255 (white). To use other
  648.     # thresholds, use the {@link #Image.point} method.
  649.     #
  650.     # @def convert(mode, matrix=None, **options)
  651.     # @param mode The requested mode.
  652.     # @param matrix An optional conversion matrix.  If given, this
  653.     #    should be 4- or 16-tuple containing floating point values.
  654.     # @param options Additional options, given as keyword arguments.
  655.     # @keyparam dither Dithering method, used when converting from
  656.     #    mode "RGB" to "P".
  657.     #    Available methods are NONE or FLOYDSTEINBERG (default).
  658.     # @keyparam palette Palette to use when converting from mode "RGB"
  659.     #    to "P".  Available palettes are WEB or ADAPTIVE.
  660.     # @keyparam colors Number of colors to use for the ADAPTIVE palette.
  661.     #    Defaults to 256.
  662.     # @return An Image object.
  663.  
  664.     def convert(self, mode=None, data=None, dither=None,
  665.                 palette=WEB, colors=256):
  666.         "Convert to other pixel format"
  667.  
  668.         if not mode:
  669.             # determine default mode
  670.             if self.mode == "P":
  671.                 self.load()
  672.                 if self.palette:
  673.                     mode = self.palette.mode
  674.                 else:
  675.                     mode = "RGB"
  676.             else:
  677.                 return self.copy()
  678.  
  679.         self.load()
  680.  
  681.         if data:
  682.             # matrix conversion
  683.             if mode not in ("L", "RGB"):
  684.                 raise ValueError("illegal conversion")
  685.             im = self.im.convert_matrix(mode, data)
  686.             return self._new(im)
  687.  
  688.         if mode == "P" and palette == ADAPTIVE:
  689.             im = self.im.quantize(colors)
  690.             return self._new(im)
  691.  
  692.         # colourspace conversion
  693.         if dither is None:
  694.             dither = FLOYDSTEINBERG
  695.  
  696.         try:
  697.             im = self.im.convert(mode, dither)
  698.         except ValueError:
  699.             try:
  700.                 # normalize source image and try again
  701.                 im = self.im.convert(getmodebase(self.mode))
  702.                 im = im.convert(mode, dither)
  703.             except KeyError:
  704.                 raise ValueError("illegal conversion")
  705.  
  706.         return self._new(im)
  707.  
  708.     def quantize(self, colors=256, method=0, kmeans=0, palette=None):
  709.  
  710.         # methods:
  711.         #    0 = median cut
  712.         #    1 = maximum coverage
  713.  
  714.         # NOTE: this functionality will be moved to the extended
  715.         # quantizer interface in a later version of PIL.
  716.  
  717.         self.load()
  718.  
  719.         if palette:
  720.             # use palette from reference image
  721.             palette.load()
  722.             if palette.mode != "P":
  723.                 raise ValueError("bad mode for palette image")
  724.             if self.mode != "RGB" and self.mode != "L":
  725.                 raise ValueError(
  726.                     "only RGB or L mode images can be quantized to a palette"
  727.                     )
  728.             im = self.im.convert("P", 1, palette.im)
  729.             return self._makeself(im)
  730.  
  731.         im = self.im.quantize(colors, method, kmeans)
  732.         return self._new(im)
  733.  
  734.     ##
  735.     # Copies this image. Use this method if you wish to paste things
  736.     # into an image, but still retain the original.
  737.     #
  738.     # @return An Image object.
  739.  
  740.     def copy(self):
  741.         "Copy raster data"
  742.  
  743.         self.load()
  744.         im = self.im.copy()
  745.         return self._new(im)
  746.  
  747.     ##
  748.     # Returns a rectangular region from this image. The box is a
  749.     # 4-tuple defining the left, upper, right, and lower pixel
  750.     # coordinate.
  751.     # <p>
  752.     # This is a lazy operation.  Changes to the source image may or
  753.     # may not be reflected in the cropped image.  To break the
  754.     # connection, call the {@link #Image.load} method on the cropped
  755.     # copy.
  756.     #
  757.     # @param The crop rectangle, as a (left, upper, right, lower)-tuple.
  758.     # @return An Image object.
  759.  
  760.     def crop(self, box=None):
  761.         "Crop region from image"
  762.  
  763.         self.load()
  764.         if box is None:
  765.             return self.copy()
  766.  
  767.         # lazy operation
  768.         return _ImageCrop(self, box)
  769.  
  770.     ##
  771.     # Configures the image file loader so it returns a version of the
  772.     # image that as closely as possible matches the given mode and
  773.     # size.  For example, you can use this method to convert a colour
  774.     # JPEG to greyscale while loading it, or to extract a 128x192
  775.     # version from a PCD file.
  776.     # <p>
  777.     # Note that this method modifies the Image object in place.  If
  778.     # the image has already been loaded, this method has no effect.
  779.     #
  780.     # @param mode The requested mode.
  781.     # @param size The requested size.
  782.  
  783.     def draft(self, mode, size):
  784.         "Configure image decoder"
  785.  
  786.         pass
  787.  
  788.     def _expand(self, xmargin, ymargin=None):
  789.         if ymargin is None:
  790.             ymargin = xmargin
  791.         self.load()
  792.         return self._new(self.im.expand(xmargin, ymargin, 0))
  793.  
  794.     ##
  795.     # Filters this image using the given filter.  For a list of
  796.     # available filters, see the <b>ImageFilter</b> module.
  797.     #
  798.     # @param filter Filter kernel.
  799.     # @return An Image object.
  800.     # @see ImageFilter
  801.  
  802.     def filter(self, filter):
  803.         "Apply environment filter to image"
  804.  
  805.         self.load()
  806.  
  807.         if callable(filter):
  808.             filter = filter()
  809.         if not hasattr(filter, "filter"):
  810.             raise TypeError("filter argument should be ImageFilter.Filter instance or class")
  811.  
  812.         if self.im.bands == 1:
  813.             return self._new(filter.filter(self.im))
  814.         # fix to handle multiband images since _imaging doesn't
  815.         ims = []
  816.         for c in range(self.im.bands):
  817.             ims.append(self._new(filter.filter(self.im.getband(c))))
  818.         return merge(self.mode, ims)
  819.  
  820.     ##
  821.     # Returns a tuple containing the name of each band in this image.
  822.     # For example, <b>getbands</b> on an RGB image returns ("R", "G", "B").
  823.     #
  824.     # @return A tuple containing band names.
  825.  
  826.     def getbands(self):
  827.         "Get band names"
  828.  
  829.         return ImageMode.getmode(self.mode).bands
  830.  
  831.     ##
  832.     # Calculates the bounding box of the non-zero regions in the
  833.     # image.
  834.     #
  835.     # @return The bounding box is returned as a 4-tuple defining the
  836.     #    left, upper, right, and lower pixel coordinate. If the image
  837.     #    is completely empty, this method returns None.
  838.  
  839.     def getbbox(self):
  840.         "Get bounding box of actual data (non-zero pixels) in image"
  841.  
  842.         self.load()
  843.         return self.im.getbbox()
  844.  
  845.     ##
  846.     # Returns a list of colors used in this image.
  847.     #
  848.     # @param maxcolors Maximum number of colors.  If this number is
  849.     #    exceeded, this method returns None.  The default limit is
  850.     #    256 colors.
  851.     # @return An unsorted list of (count, pixel) values.
  852.  
  853.     def getcolors(self, maxcolors=256):
  854.         "Get colors from image, up to given limit"
  855.  
  856.         self.load()
  857.         if self.mode in ("1", "L", "P"):
  858.             h = self.im.histogram()
  859.             out = []
  860.             for i in range(256):
  861.                 if h[i]:
  862.                     out.append((h[i], i))
  863.             if len(out) > maxcolors:
  864.                 return None
  865.             return out
  866.         return self.im.getcolors(maxcolors)
  867.  
  868.     ##
  869.     # Returns the contents of this image as a sequence object
  870.     # containing pixel values.  The sequence object is flattened, so
  871.     # that values for line one follow directly after the values of
  872.     # line zero, and so on.
  873.     # <p>
  874.     # Note that the sequence object returned by this method is an
  875.     # internal PIL data type, which only supports certain sequence
  876.     # operations.  To convert it to an ordinary sequence (e.g. for
  877.     # printing), use <b>list(im.getdata())</b>.
  878.     #
  879.     # @param band What band to return.  The default is to return
  880.     #    all bands.  To return a single band, pass in the index
  881.     #    value (e.g. 0 to get the "R" band from an "RGB" image).
  882.     # @return A sequence-like object.
  883.  
  884.     def getdata(self, band = None):
  885.         "Get image data as sequence object."
  886.  
  887.         self.load()
  888.         if band is not None:
  889.             return self.im.getband(band)
  890.         return self.im # could be abused
  891.  
  892.     ##
  893.     # Gets the the minimum and maximum pixel values for each band in
  894.     # the image.
  895.     #
  896.     # @return For a single-band image, a 2-tuple containing the
  897.     #    minimum and maximum pixel value.  For a multi-band image,
  898.     #    a tuple containing one 2-tuple for each band.
  899.  
  900.     def getextrema(self):
  901.         "Get min/max value"
  902.  
  903.         self.load()
  904.         if self.im.bands > 1:
  905.             extrema = []
  906.             for i in range(self.im.bands):
  907.                 extrema.append(self.im.getband(i).getextrema())
  908.             return tuple(extrema)
  909.         return self.im.getextrema()
  910.  
  911.     ##
  912.     # Returns a PyCObject that points to the internal image memory.
  913.     #
  914.     # @return A PyCObject object.
  915.  
  916.     def getim(self):
  917.         "Get PyCObject pointer to internal image memory"
  918.  
  919.         self.load()
  920.         return self.im.ptr
  921.  
  922.  
  923.     ##
  924.     # Returns the image palette as a list.
  925.     #
  926.     # @return A list of color values [r, g, b, ...], or None if the
  927.     #    image has no palette.
  928.  
  929.     def getpalette(self):
  930.         "Get palette contents."
  931.  
  932.         self.load()
  933.         try:
  934.             return map(ord, self.im.getpalette())
  935.         except ValueError:
  936.             return None # no palette
  937.  
  938.  
  939.     ##
  940.     # Returns the pixel value at a given position.
  941.     #
  942.     # @param xy The coordinate, given as (x, y).
  943.     # @return The pixel value.  If the image is a multi-layer image,
  944.     #    this method returns a tuple.
  945.  
  946.     def getpixel(self, xy):
  947.         "Get pixel value"
  948.  
  949.         self.load()
  950.         return self.im.getpixel(xy)
  951.  
  952.     ##
  953.     # Returns the horizontal and vertical projection.
  954.     #
  955.     # @return Two sequences, indicating where there are non-zero
  956.     #     pixels along the X-axis and the Y-axis, respectively.
  957.  
  958.     def getprojection(self):
  959.         "Get projection to x and y axes"
  960.  
  961.         self.load()
  962.         x, y = self.im.getprojection()
  963.         return map(ord, x), map(ord, y)
  964.  
  965.     ##
  966.     # Returns a histogram for the image. The histogram is returned as
  967.     # a list of pixel counts, one for each pixel value in the source
  968.     # image. If the image has more than one band, the histograms for
  969.     # all bands are concatenated (for example, the histogram for an
  970.     # "RGB" image contains 768 values).
  971.     # <p>
  972.     # A bilevel image (mode "1") is treated as a greyscale ("L") image
  973.     # by this method.
  974.     # <p>
  975.     # If a mask is provided, the method returns a histogram for those
  976.     # parts of the image where the mask image is non-zero. The mask
  977.     # image must have the same size as the image, and be either a
  978.     # bi-level image (mode "1") or a greyscale image ("L").
  979.     #
  980.     # @def histogram(mask=None)
  981.     # @param mask An optional mask.
  982.     # @return A list containing pixel counts.
  983.  
  984.     def histogram(self, mask=None, extrema=None):
  985.         "Take histogram of image"
  986.  
  987.         self.load()
  988.         if mask:
  989.             mask.load()
  990.             return self.im.histogram((0, 0), mask.im)
  991.         if self.mode in ("I", "F"):
  992.             if extrema is None:
  993.                 extrema = self.getextrema()
  994.             return self.im.histogram(extrema)
  995.         return self.im.histogram()
  996.  
  997.     ##
  998.     # (Deprecated) Returns a copy of the image where the data has been
  999.     # offset by the given distances. Data wraps around the edges. If
  1000.     # yoffset is omitted, it is assumed to be equal to xoffset.
  1001.     # <p>
  1002.     # This method is deprecated. New code should use the <b>offset</b>
  1003.     # function in the <b>ImageChops</b> module.
  1004.     #
  1005.     # @param xoffset The horizontal distance.
  1006.     # @param yoffset The vertical distance.  If omitted, both
  1007.     #    distances are set to the same value.
  1008.     # @return An Image object.
  1009.  
  1010.     def offset(self, xoffset, yoffset=None):
  1011.         "(deprecated) Offset image in horizontal and/or vertical direction"
  1012.         if warnings:
  1013.             warnings.warn(
  1014.                 "'offset' is deprecated; use 'ImageChops.offset' instead",
  1015.                 DeprecationWarning, stacklevel=2
  1016.                 )
  1017.         import ImageChops
  1018.         return ImageChops.offset(self, xoffset, yoffset)
  1019.  
  1020.     ##
  1021.     # Pastes another image into this image. The box argument is either
  1022.     # a 2-tuple giving the upper left corner, a 4-tuple defining the
  1023.     # left, upper, right, and lower pixel coordinate, or None (same as
  1024.     # (0, 0)).  If a 4-tuple is given, the size of the pasted image
  1025.     # must match the size of the region.
  1026.     # <p>
  1027.     # If the modes don't match, the pasted image is converted to the
  1028.     # mode of this image (see the {@link #Image.convert} method for
  1029.     # details).
  1030.     # <p>
  1031.     # Instead of an image, the source can be a integer or tuple
  1032.     # containing pixel values.  The method then fills the region
  1033.     # with the given colour.  When creating RGB images, you can
  1034.     # also use colour strings as supported by the ImageColor module.
  1035.     # <p>
  1036.     # If a mask is given, this method updates only the regions
  1037.     # indicated by the mask.  You can use either "1", "L" or "RGBA"
  1038.     # images (in the latter case, the alpha band is used as mask).
  1039.     # Where the mask is 255, the given image is copied as is.  Where
  1040.     # the mask is 0, the current value is preserved.  Intermediate
  1041.     # values can be used for transparency effects.
  1042.     # <p>
  1043.     # Note that if you paste an "RGBA" image, the alpha band is
  1044.     # ignored.  You can work around this by using the same image as
  1045.     # both source image and mask.
  1046.     #
  1047.     # @param im Source image or pixel value (integer or tuple).
  1048.     # @param box An optional 4-tuple giving the region to paste into.
  1049.     #    If a 2-tuple is used instead, it's treated as the upper left
  1050.     #    corner.  If omitted or None, the source is pasted into the
  1051.     #    upper left corner.
  1052.     #    <p>
  1053.     #    If an image is given as the second argument and there is no
  1054.     #    third, the box defaults to (0, 0), and the second argument
  1055.     #    is interpreted as a mask image.
  1056.     # @param mask An optional mask image.
  1057.     # @return An Image object.
  1058.  
  1059.     def paste(self, im, box=None, mask=None):
  1060.         "Paste other image into region"
  1061.  
  1062.         if isImageType(box) and mask is None:
  1063.             # abbreviated paste(im, mask) syntax
  1064.             mask = box; box = None
  1065.  
  1066.         if box is None:
  1067.             # cover all of self
  1068.             box = (0, 0) + self.size
  1069.  
  1070.         if len(box) == 2:
  1071.             # lower left corner given; get size from image or mask
  1072.             if isImageType(im):
  1073.                 size = im.size
  1074.             elif isImageType(mask):
  1075.                 size = mask.size
  1076.             else:
  1077.                 # FIXME: use self.size here?
  1078.                 raise ValueError(
  1079.                     "cannot determine region size; use 4-item box"
  1080.                     )
  1081.             box = box + (box[0]+size[0], box[1]+size[1])
  1082.  
  1083.         if isStringType(im):
  1084.             import ImageColor
  1085.             im = ImageColor.getcolor(im, self.mode)
  1086.  
  1087.         elif isImageType(im):
  1088.             im.load()
  1089.             if self.mode != im.mode:
  1090.                 if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"):
  1091.                     # should use an adapter for this!
  1092.                     im = im.convert(self.mode)
  1093.             im = im.im
  1094.  
  1095.         self.load()
  1096.         if self.readonly:
  1097.             self._copy()
  1098.  
  1099.         if mask:
  1100.             mask.load()
  1101.             self.im.paste(im, box, mask.im)
  1102.         else:
  1103.             self.im.paste(im, box)
  1104.  
  1105.     ##
  1106.     # Maps this image through a lookup table or function.
  1107.     #
  1108.     # @param lut A lookup table, containing 256 values per band in the
  1109.     #    image. A function can be used instead, it should take a single
  1110.     #    argument. The function is called once for each possible pixel
  1111.     #    value, and the resulting table is applied to all bands of the
  1112.     #    image.
  1113.     # @param mode Output mode (default is same as input).  In the
  1114.     #    current version, this can only be used if the source image
  1115.     #    has mode "L" or "P", and the output has mode "1".
  1116.     # @return An Image object.
  1117.  
  1118.     def point(self, lut, mode=None):
  1119.         "Map image through lookup table"
  1120.  
  1121.         self.load()
  1122.  
  1123.         if isinstance(lut, ImagePointHandler):
  1124.             return lut.point(self)
  1125.  
  1126.         if not isSequenceType(lut):
  1127.             # if it isn't a list, it should be a function
  1128.             if self.mode in ("I", "I;16", "F"):
  1129.                 # check if the function can be used with point_transform
  1130.                 scale, offset = _getscaleoffset(lut)
  1131.                 return self._new(self.im.point_transform(scale, offset))
  1132.             # for other modes, convert the function to a table
  1133.             lut = map(lut, range(256)) * self.im.bands
  1134.  
  1135.         if self.mode == "F":
  1136.             # FIXME: _imaging returns a confusing error message for this case
  1137.             raise ValueError("point operation not supported for this mode")
  1138.  
  1139.         return self._new(self.im.point(lut, mode))
  1140.  
  1141.     ##
  1142.     # Adds or replaces the alpha layer in this image.  If the image
  1143.     # does not have an alpha layer, it's converted to "LA" or "RGBA".
  1144.     # The new layer must be either "L" or "1".
  1145.     #
  1146.     # @param im The new alpha layer.  This can either be an "L" or "1"
  1147.     #    image having the same size as this image, or an integer or
  1148.     #    other color value.
  1149.  
  1150.     def putalpha(self, alpha):
  1151.         "Set alpha layer"
  1152.  
  1153.         self.load()
  1154.         if self.readonly:
  1155.             self._copy()
  1156.  
  1157.         if self.mode not in ("LA", "RGBA"):
  1158.             # attempt to promote self to a matching alpha mode
  1159.             try:
  1160.                 mode = getmodebase(self.mode) + "A"
  1161.                 try:
  1162.                     self.im.setmode(mode)
  1163.                 except (AttributeError, ValueError):
  1164.                     # do things the hard way
  1165.                     im = self.im.convert(mode)
  1166.                     if im.mode not in ("LA", "RGBA"):
  1167.                         raise ValueError # sanity check
  1168.                     self.im = im
  1169.                 self.mode = self.im.mode
  1170.             except (KeyError, ValueError):
  1171.                 raise ValueError("illegal image mode")
  1172.  
  1173.         if self.mode == "LA":
  1174.             band = 1
  1175.         else:
  1176.             band = 3
  1177.  
  1178.         if isImageType(alpha):
  1179.             # alpha layer
  1180.             if alpha.mode not in ("1", "L"):
  1181.                 raise ValueError("illegal image mode")
  1182.             alpha.load()
  1183.             if alpha.mode == "1":
  1184.                 alpha = alpha.convert("L")
  1185.         else:
  1186.             # constant alpha
  1187.             try:
  1188.                 self.im.fillband(band, alpha)
  1189.             except (AttributeError, ValueError):
  1190.                 # do things the hard way
  1191.                 alpha = new("L", self.size, alpha)
  1192.             else:
  1193.                 return
  1194.  
  1195.         self.im.putband(alpha.im, band)
  1196.  
  1197.     ##
  1198.     # Copies pixel data to this image.  This method copies data from a
  1199.     # sequence object into the image, starting at the upper left
  1200.     # corner (0, 0), and continuing until either the image or the
  1201.     # sequence ends.  The scale and offset values are used to adjust
  1202.     # the sequence values: <b>pixel = value*scale + offset</b>.
  1203.     #
  1204.     # @param data A sequence object.
  1205.     # @param scale An optional scale value.  The default is 1.0.
  1206.     # @param offset An optional offset value.  The default is 0.0.
  1207.  
  1208.     def putdata(self, data, scale=1.0, offset=0.0):
  1209.         "Put data from a sequence object into an image."
  1210.  
  1211.         self.load()
  1212.         if self.readonly:
  1213.             self._copy()
  1214.  
  1215.         self.im.putdata(data, scale, offset)
  1216.  
  1217.     ##
  1218.     # Attaches a palette to this image.  The image must be a "P" or
  1219.     # "L" image, and the palette sequence must contain 768 integer
  1220.     # values, where each group of three values represent the red,
  1221.     # green, and blue values for the corresponding pixel
  1222.     # index. Instead of an integer sequence, you can use an 8-bit
  1223.     # string.
  1224.     #
  1225.     # @def putpalette(data)
  1226.     # @param data A palette sequence (either a list or a string).
  1227.  
  1228.     def putpalette(self, data, rawmode="RGB"):
  1229.         "Put palette data into an image."
  1230.  
  1231.         if self.mode not in ("L", "P"):
  1232.             raise ValueError("illegal image mode")
  1233.         self.load()
  1234.         if isinstance(data, ImagePalette.ImagePalette):
  1235.             palette = ImagePalette.raw(data.rawmode, data.palette)
  1236.         else:
  1237.             if not isStringType(data):
  1238.                 data = string.join(map(chr, data), "")
  1239.             palette = ImagePalette.raw(rawmode, data)
  1240.         self.mode = "P"
  1241.         self.palette = palette
  1242.         self.palette.mode = "RGB"
  1243.         self.load() # install new palette
  1244.  
  1245.     ##
  1246.     # Modifies the pixel at the given position. The colour is given as
  1247.     # a single numerical value for single-band images, and a tuple for
  1248.     # multi-band images.
  1249.     # <p>
  1250.     # Note that this method is relatively slow.  For more extensive
  1251.     # changes, use {@link #Image.paste} or the <b>ImageDraw</b> module
  1252.     # instead.
  1253.     #
  1254.     # @param xy The pixel coordinate, given as (x, y).
  1255.     # @param value The pixel value.
  1256.     # @see #Image.paste
  1257.     # @see #Image.putdata
  1258.     # @see ImageDraw
  1259.  
  1260.     def putpixel(self, xy, value):
  1261.         "Set pixel value"
  1262.  
  1263.         self.load()
  1264.         if self.readonly:
  1265.             self._copy()
  1266.  
  1267.         return self.im.putpixel(xy, value)
  1268.  
  1269.     ##
  1270.     # Returns a resized copy of this image.
  1271.     #
  1272.     # @def resize(size, filter=NEAREST)
  1273.     # @param size The requested size in pixels, as a 2-tuple:
  1274.     #    (width, height).
  1275.     # @param filter An optional resampling filter.  This can be
  1276.     #    one of <b>NEAREST</b> (use nearest neighbour), <b>BILINEAR</b>
  1277.     #    (linear interpolation in a 2x2 environment), <b>BICUBIC</b>
  1278.     #    (cubic spline interpolation in a 4x4 environment), or
  1279.     #    <b>ANTIALIAS</b> (a high-quality downsampling filter).
  1280.     #    If omitted, or if the image has mode "1" or "P", it is
  1281.     #    set <b>NEAREST</b>.
  1282.     # @return An Image object.
  1283.  
  1284.     def resize(self, size, resample=NEAREST):
  1285.         "Resize image"
  1286.  
  1287.         if resample not in (NEAREST, BILINEAR, BICUBIC, ANTIALIAS):
  1288.             raise ValueError("unknown resampling filter")
  1289.  
  1290.         self.load()
  1291.  
  1292.         if self.mode in ("1", "P"):
  1293.             resample = NEAREST
  1294.  
  1295.         if resample == ANTIALIAS:
  1296.             # requires stretch support (imToolkit & PIL 1.1.3)
  1297.             try:
  1298.                 im = self.im.stretch(size, resample)
  1299.             except AttributeError:
  1300.                 raise ValueError("unsupported resampling filter")
  1301.         else:
  1302.             im = self.im.resize(size, resample)
  1303.  
  1304.         return self._new(im)
  1305.  
  1306.     ##
  1307.     # Returns a rotated copy of this image.  This method returns a
  1308.     # copy of this image, rotated the given number of degrees counter
  1309.     # clockwise around its centre.
  1310.     #
  1311.     # @def rotate(angle, filter=NEAREST)
  1312.     # @param angle In degrees counter clockwise.
  1313.     # @param filter An optional resampling filter.  This can be
  1314.     #    one of <b>NEAREST</b> (use nearest neighbour), <b>BILINEAR</b>
  1315.     #    (linear interpolation in a 2x2 environment), or <b>BICUBIC</b>
  1316.     #    (cubic spline interpolation in a 4x4 environment).
  1317.     #    If omitted, or if the image has mode "1" or "P", it is
  1318.     #    set <b>NEAREST</b>.
  1319.     # @param expand Optional expansion flag.  If true, expands the output
  1320.     #    image to make it large enough to hold the entire rotated image.
  1321.     #    If false or omitted, make the output image the same size as the
  1322.     #    input image.
  1323.     # @return An Image object.
  1324.  
  1325.     def rotate(self, angle, resample=NEAREST, expand=0):
  1326.         "Rotate image.  Angle given as degrees counter-clockwise."
  1327.  
  1328.         if expand:
  1329.             import math
  1330.             angle = -angle * math.pi / 180
  1331.             matrix = [
  1332.                  math.cos(angle), math.sin(angle), 0.0,
  1333.                 -math.sin(angle), math.cos(angle), 0.0
  1334.                  ]
  1335.             def transform(x, y, (a, b, c, d, e, f)=matrix):
  1336.                 return a*x + b*y + c, d*x + e*y + f
  1337.  
  1338.             # calculate output size
  1339.             w, h = self.size
  1340.             xx = []
  1341.             yy = []
  1342.             for x, y in ((0, 0), (w, 0), (w, h), (0, h)):
  1343.                 x, y = transform(x, y)
  1344.                 xx.append(x)
  1345.                 yy.append(y)
  1346.             w = int(math.ceil(max(xx)) - math.floor(min(xx)))
  1347.             h = int(math.ceil(max(yy)) - math.floor(min(yy)))
  1348.  
  1349.             # adjust center
  1350.             x, y = transform(w / 2.0, h / 2.0)
  1351.             matrix[2] = self.size[0] / 2.0 - x
  1352.             matrix[5] = self.size[1] / 2.0 - y
  1353.  
  1354.             return self.transform((w, h), AFFINE, matrix, resample)
  1355.  
  1356.         if resample not in (NEAREST, BILINEAR, BICUBIC):
  1357.             raise ValueError("unknown resampling filter")
  1358.  
  1359.         self.load()
  1360.  
  1361.         if self.mode in ("1", "P"):
  1362.             resample = NEAREST
  1363.  
  1364.         return self._new(self.im.rotate(angle, resample))
  1365.  
  1366.     ##
  1367.     # Saves this image under the given filename.  If no format is
  1368.     # specified, the format to use is determined from the filename
  1369.     # extension, if possible.
  1370.     # <p>
  1371.     # Keyword options can be used to provide additional instructions
  1372.     # to the writer. If a writer doesn't recognise an option, it is
  1373.     # silently ignored. The available options are described later in
  1374.     # this handbook.
  1375.     # <p>
  1376.     # You can use a file object instead of a filename. In this case,
  1377.     # you must always specify the format. The file object must
  1378.     # implement the <b>seek</b>, <b>tell</b>, and <b>write</b>
  1379.     # methods, and be opened in binary mode.
  1380.     #
  1381.     # @def save(file, format=None, **options)
  1382.     # @param file File name or file object.
  1383.     # @param format Optional format override.  If omitted, the
  1384.     #    format to use is determined from the filename extension.
  1385.     #    If a file object was used instead of a filename, this
  1386.     #    parameter should always be used.
  1387.     # @param **options Extra parameters to the image writer.
  1388.     # @return None
  1389.     # @exception KeyError If the output format could not be determined
  1390.     #    from the file name.  Use the format option to solve this.
  1391.     # @exception IOError If the file could not be written.  The file
  1392.     #    may have been created, and may contain partial data.
  1393.  
  1394.     def save(self, fp, format=None, **params):
  1395.         "Save image to file or stream"
  1396.  
  1397.         if isStringType(fp):
  1398.             filename = fp
  1399.         else:
  1400.             if hasattr(fp, "name") and isStringType(fp.name):
  1401.                 filename = fp.name
  1402.             else:
  1403.                 filename = ""
  1404.  
  1405.         # may mutate self!
  1406.         self.load()
  1407.  
  1408.         self.encoderinfo = params
  1409.         self.encoderconfig = ()
  1410.  
  1411.         preinit()
  1412.  
  1413.         ext = string.lower(os.path.splitext(filename)[1])
  1414.  
  1415.         if not format:
  1416.             try:
  1417.                 format = EXTENSION[ext]
  1418.             except KeyError:
  1419.                 init()
  1420.                 try:
  1421.                     format = EXTENSION[ext]
  1422.                 except KeyError:
  1423.                     raise KeyError(ext) # unknown extension
  1424.  
  1425.         try:
  1426.             save_handler = SAVE[string.upper(format)]
  1427.         except KeyError:
  1428.             init()
  1429.             save_handler = SAVE[string.upper(format)] # unknown format
  1430.  
  1431.         if isStringType(fp):
  1432.             import __builtin__
  1433.             fp = __builtin__.open(fp, "wb")
  1434.             close = 1
  1435.         else:
  1436.             close = 0
  1437.  
  1438.         try:
  1439.             save_handler(self, fp, filename)
  1440.         finally:
  1441.             # do what we can to clean up
  1442.             if close:
  1443.                 fp.close()
  1444.  
  1445.     ##
  1446.     # Seeks to the given frame in this sequence file. If you seek
  1447.     # beyond the end of the sequence, the method raises an
  1448.     # <b>EOFError</b> exception. When a sequence file is opened, the
  1449.     # library automatically seeks to frame 0.
  1450.     # <p>
  1451.     # Note that in the current version of the library, most sequence
  1452.     # formats only allows you to seek to the next frame.
  1453.     #
  1454.     # @param frame Frame number, starting at 0.
  1455.     # @exception EOFError If the call attempts to seek beyond the end
  1456.     #     of the sequence.
  1457.     # @see #Image.tell
  1458.  
  1459.     def seek(self, frame):
  1460.         "Seek to given frame in sequence file"
  1461.  
  1462.         # overridden by file handlers
  1463.         if frame != 0:
  1464.             raise EOFError
  1465.  
  1466.     ##
  1467.     # Displays this image. This method is mainly intended for
  1468.     # debugging purposes.
  1469.     # <p>
  1470.     # On Unix platforms, this method saves the image to a temporary
  1471.     # PPM file, and calls the <b>xv</b> utility.
  1472.     # <p>
  1473.     # On Windows, it saves the image to a temporary BMP file, and uses
  1474.     # the standard BMP display utility to show it (usually Paint).
  1475.     #
  1476.     # @def show(title=None)
  1477.     # @param title Optional title to use for the image window,
  1478.     #    where possible.
  1479.  
  1480.     def show(self, title=None, command=None):
  1481.         "Display image (for debug purposes only)"
  1482.  
  1483.         _show(self, title=title, command=command)
  1484.  
  1485.     ##
  1486.     # Split this image into individual bands. This method returns a
  1487.     # tuple of individual image bands from an image. For example,
  1488.     # splitting an "RGB" image creates three new images each
  1489.     # containing a copy of one of the original bands (red, green,
  1490.     # blue).
  1491.     #
  1492.     # @return A tuple containing bands.
  1493.  
  1494.     def split(self):
  1495.         "Split image into bands"
  1496.  
  1497.         if self.im.bands == 1:
  1498.             ims = [self.copy()]
  1499.         else:
  1500.             ims = []
  1501.             self.load()
  1502.             for i in range(self.im.bands):
  1503.                 ims.append(self._new(self.im.getband(i)))
  1504.         return tuple(ims)
  1505.  
  1506.     ##
  1507.     # Returns the current frame number.
  1508.     #
  1509.     # @return Frame number, starting with 0.
  1510.     # @see #Image.seek
  1511.  
  1512.     def tell(self):
  1513.         "Return current frame number"
  1514.  
  1515.         return 0
  1516.  
  1517.     ##
  1518.     # Make this image into a thumbnail.  This method modifies the
  1519.     # image to contain a thumbnail version of itself, no larger than
  1520.     # the given size.  This method calculates an appropriate thumbnail
  1521.     # size to preserve the aspect of the image, calls the {@link
  1522.     # #Image.draft} method to configure the file reader (where
  1523.     # applicable), and finally resizes the image.
  1524.     # <p>
  1525.     # Note that the bilinear and bicubic filters in the current
  1526.     # version of PIL are not well-suited for thumbnail generation.
  1527.     # You should use <b>ANTIALIAS</b> unless speed is much more
  1528.     # important than quality.
  1529.     # <p>
  1530.     # Also note that this function modifies the Image object in place.
  1531.     # If you need to use the full resolution image as well, apply this
  1532.     # method to a {@link #Image.copy} of the original image.
  1533.     #
  1534.     # @param size Requested size.
  1535.     # @param resample Optional resampling filter.  This can be one
  1536.     #    of <b>NEAREST</b>, <b>BILINEAR</b>, <b>BICUBIC</b>, or
  1537.     #    <b>ANTIALIAS</b> (best quality).  If omitted, it defaults
  1538.     #    to <b>NEAREST</b> (this will be changed to ANTIALIAS in a
  1539.     #    future version).
  1540.     # @return None
  1541.  
  1542.     def thumbnail(self, size, resample=NEAREST):
  1543.         "Create thumbnail representation (modifies image in place)"
  1544.  
  1545.         # FIXME: the default resampling filter will be changed
  1546.         # to ANTIALIAS in future versions
  1547.  
  1548.         # preserve aspect ratio
  1549.         x, y = self.size
  1550.         if x > size[0]: y = max(y * size[0] / x, 1); x = size[0]
  1551.         if y > size[1]: x = max(x * size[1] / y, 1); y = size[1]
  1552.         size = x, y
  1553.  
  1554.         if size == self.size:
  1555.             return
  1556.  
  1557.         self.draft(None, size)
  1558.  
  1559.         self.load()
  1560.  
  1561.         try:
  1562.             im = self.resize(size, resample)
  1563.         except ValueError:
  1564.             if resample != ANTIALIAS:
  1565.                 raise
  1566.             im = self.resize(size, NEAREST) # fallback
  1567.  
  1568.         self.im = im.im
  1569.         self.mode = im.mode
  1570.         self.size = size
  1571.  
  1572.         self.readonly = 0
  1573.  
  1574.     # FIXME: the different tranform methods need further explanation
  1575.     # instead of bloating the method docs, add a separate chapter.
  1576.  
  1577.     ##
  1578.     # Transforms this image.  This method creates a new image with the
  1579.     # given size, and the same mode as the original, and copies data
  1580.     # to the new image using the given transform.
  1581.     # <p>
  1582.     # @def transform(size, method, data, resample=NEAREST)
  1583.     # @param size The output size.
  1584.     # @param method The transformation method.  This is one of
  1585.     #   <b>EXTENT</b> (cut out a rectangular subregion), <b>AFFINE</b>
  1586.     #   (affine transform), <b>PERSPECTIVE</b> (perspective
  1587.     #   transform), <b>QUAD</b> (map a quadrilateral to a
  1588.     #   rectangle), or <b>MESH</b> (map a number of source quadrilaterals
  1589.     #   in one operation).
  1590.     # @param data Extra data to the transformation method.
  1591.     # @param resample Optional resampling filter.  It can be one of
  1592.     #    <b>NEAREST</b> (use nearest neighbour), <b>BILINEAR</b>
  1593.     #    (linear interpolation in a 2x2 environment), or
  1594.     #    <b>BICUBIC</b> (cubic spline interpolation in a 4x4
  1595.     #    environment). If omitted, or if the image has mode
  1596.     #    "1" or "P", it is set to <b>NEAREST</b>.
  1597.     # @return An Image object.
  1598.  
  1599.     def transform(self, size, method, data=None, resample=NEAREST, fill=1):
  1600.         "Transform image"
  1601.  
  1602.         if isinstance(method, ImageTransformHandler):
  1603.             return method.transform(size, self, resample=resample, fill=fill)
  1604.         if hasattr(method, "getdata"):
  1605.             # compatibility w. old-style transform objects
  1606.             method, data = method.getdata()
  1607.         if data is None:
  1608.             raise ValueError("missing method data")
  1609.         im = new(self.mode, size, None)
  1610.         if method == MESH:
  1611.             # list of quads
  1612.             for box, quad in data:
  1613.                 im.__transformer(box, self, QUAD, quad, resample, fill)
  1614.         else:
  1615.             im.__transformer((0, 0)+size, self, method, data, resample, fill)
  1616.  
  1617.         return im
  1618.  
  1619.     def __transformer(self, box, image, method, data,
  1620.                       resample=NEAREST, fill=1):
  1621.  
  1622.         # FIXME: this should be turned into a lazy operation (?)
  1623.  
  1624.         w = box[2]-box[0]
  1625.         h = box[3]-box[1]
  1626.  
  1627.         if method == AFFINE:
  1628.             # change argument order to match implementation
  1629.             data = (data[2], data[0], data[1],
  1630.                     data[5], data[3], data[4])
  1631.         elif method == EXTENT:
  1632.             # convert extent to an affine transform
  1633.             x0, y0, x1, y1 = data
  1634.             xs = float(x1 - x0) / w
  1635.             ys = float(y1 - y0) / h
  1636.             method = AFFINE
  1637.             data = (x0 + xs/2, xs, 0, y0 + ys/2, 0, ys)
  1638.         elif method == PERSPECTIVE:
  1639.             # change argument order to match implementation
  1640.             data = (data[2], data[0], data[1],
  1641.                     data[5], data[3], data[4],
  1642.                     data[6], data[7])
  1643.         elif method == QUAD:
  1644.             # quadrilateral warp.  data specifies the four corners
  1645.             # given as NW, SW, SE, and NE.
  1646.             nw = data[0:2]; sw = data[2:4]; se = data[4:6]; ne = data[6:8]
  1647.             x0, y0 = nw; As = 1.0 / w; At = 1.0 / h
  1648.             data = (x0, (ne[0]-x0)*As, (sw[0]-x0)*At,
  1649.                     (se[0]-sw[0]-ne[0]+x0)*As*At,
  1650.                     y0, (ne[1]-y0)*As, (sw[1]-y0)*At,
  1651.                     (se[1]-sw[1]-ne[1]+y0)*As*At)
  1652.         else:
  1653.             raise ValueError("unknown transformation method")
  1654.  
  1655.         if resample not in (NEAREST, BILINEAR, BICUBIC):
  1656.             raise ValueError("unknown resampling filter")
  1657.  
  1658.         image.load()
  1659.  
  1660.         self.load()
  1661.  
  1662.         if image.mode in ("1", "P"):
  1663.             resample = NEAREST
  1664.  
  1665.         self.im.transform2(box, image.im, method, data, resample, fill)
  1666.  
  1667.     ##
  1668.     # Returns a flipped or rotated copy of this image.
  1669.     #
  1670.     # @param method One of <b>FLIP_LEFT_RIGHT</b>, <b>FLIP_TOP_BOTTOM</b>,
  1671.     # <b>ROTATE_90</b>, <b>ROTATE_180</b>, or <b>ROTATE_270</b>.
  1672.  
  1673.     def transpose(self, method):
  1674.         "Transpose image (flip or rotate in 90 degree steps)"
  1675.  
  1676.         self.load()
  1677.         im = self.im.transpose(method)
  1678.         return self._new(im)
  1679.  
  1680. # --------------------------------------------------------------------
  1681. # Lazy operations
  1682.  
  1683. class _ImageCrop(Image):
  1684.  
  1685.     def __init__(self, im, box):
  1686.  
  1687.         Image.__init__(self)
  1688.  
  1689.         x0, y0, x1, y1 = box
  1690.         if x1 < x0:
  1691.             x1 = x0
  1692.         if y1 < y0:
  1693.             y1 = y0
  1694.  
  1695.         self.mode = im.mode
  1696.         self.size = x1-x0, y1-y0
  1697.  
  1698.         self.__crop = x0, y0, x1, y1
  1699.  
  1700.         self.im = im.im
  1701.  
  1702.     def load(self):
  1703.  
  1704.         # lazy evaluation!
  1705.         if self.__crop:
  1706.             self.im = self.im.crop(self.__crop)
  1707.             self.__crop = None
  1708.  
  1709.         if self.im:
  1710.             return self.im.pixel_access(self.readonly)
  1711.  
  1712.         # FIXME: future versions should optimize crop/paste
  1713.         # sequences!
  1714.  
  1715. # --------------------------------------------------------------------
  1716. # Abstract handlers.
  1717.  
  1718. class ImagePointHandler:
  1719.     # used as a mixin by point transforms (for use with im.point)
  1720.     pass
  1721.  
  1722. class ImageTransformHandler:
  1723.     # used as a mixin by geometry transforms (for use with im.transform)
  1724.     pass
  1725.  
  1726. # --------------------------------------------------------------------
  1727. # Factories
  1728.  
  1729. #
  1730. # Debugging
  1731.  
  1732. def _wedge():
  1733.     "Create greyscale wedge (for debugging only)"
  1734.  
  1735.     return Image()._new(core.wedge("L"))
  1736.  
  1737. ##
  1738. # Creates a new image with the given mode and size.
  1739. #
  1740. # @param mode The mode to use for the new image.
  1741. # @param size A 2-tuple, containing (width, height) in pixels.
  1742. # @param color What colour to use for the image.  Default is black.
  1743. #    If given, this should be a single integer or floating point value
  1744. #    for single-band modes, and a tuple for multi-band modes (one value
  1745. #    per band).  When creating RGB images, you can also use colour
  1746. #    strings as supported by the ImageColor module.  If the colour is
  1747. #    None, the image is not initialised.
  1748. # @return An Image object.
  1749.  
  1750. def new(mode, size, color=0):
  1751.     "Create a new image"
  1752.  
  1753.     if color is None:
  1754.         # don't initialize
  1755.         return Image()._new(core.new(mode, size))
  1756.  
  1757.     if isStringType(color):
  1758.         # css3-style specifier
  1759.  
  1760.         import ImageColor
  1761.         color = ImageColor.getcolor(color, mode)
  1762.  
  1763.     return Image()._new(core.fill(mode, size, color))
  1764.  
  1765. ##
  1766. # Creates an image memory from pixel data in a string.
  1767. # <p>
  1768. # In its simplest form, this function takes three arguments
  1769. # (mode, size, and unpacked pixel data).
  1770. # <p>
  1771. # You can also use any pixel decoder supported by PIL.  For more
  1772. # information on available decoders, see the section <a
  1773. # href="pil-decoder.htm"><i>Writing Your Own File Decoder</i></a>.
  1774. # <p>
  1775. # Note that this function decodes pixel data only, not entire images.
  1776. # If you have an entire image in a string, wrap it in a
  1777. # <b>StringIO</b> object, and use {@link #open} to load it.
  1778. #
  1779. # @param mode The image mode.
  1780. # @param size The image size.
  1781. # @param data An 8-bit string containing raw data for the given mode.
  1782. # @param decoder_name What decoder to use.
  1783. # @param *args Additional parameters for the given decoder.
  1784. # @return An Image object.
  1785.  
  1786. def fromstring(mode, size, data, decoder_name="raw", *args):
  1787.     "Load image from string"
  1788.  
  1789.     # may pass tuple instead of argument list
  1790.     if len(args) == 1 and isTupleType(args[0]):
  1791.         args = args[0]
  1792.  
  1793.     if decoder_name == "raw" and args == ():
  1794.         args = mode
  1795.  
  1796.     im = new(mode, size)
  1797.     im.fromstring(data, decoder_name, args)
  1798.     return im
  1799.  
  1800. ##
  1801. # (New in 1.1.4) Creates an image memory from pixel data in a string
  1802. # or byte buffer.
  1803. # <p>
  1804. # This function is similar to {@link #fromstring}, but uses data in
  1805. # the byte buffer, where possible.  This means that changes to the
  1806. # original buffer object are reflected in this image).  Not all modes
  1807. # can share memory; supported modes include "L", "RGBX", "RGBA", and
  1808. # "CMYK".
  1809. # <p>
  1810. # Note that this function decodes pixel data only, not entire images.
  1811. # If you have an entire image file in a string, wrap it in a
  1812. # <b>StringIO</b> object, and use {@link #open} to load it.
  1813. # <p>
  1814. # In the current version, the default parameters used for the "raw"
  1815. # decoder differs from that used for {@link fromstring}.  This is a
  1816. # bug, and will probably be fixed in a future release.  The current
  1817. # release issues a warning if you do this; to disable the warning,
  1818. # you should provide the full set of parameters.  See below for
  1819. # details.
  1820. #
  1821. # @param mode The image mode.
  1822. # @param size The image size.
  1823. # @param data An 8-bit string or other buffer object containing raw
  1824. #     data for the given mode.
  1825. # @param decoder_name What decoder to use.
  1826. # @param *args Additional parameters for the given decoder.  For the
  1827. #     default encoder ("raw"), it's recommended that you provide the
  1828. #     full set of parameters:
  1829. #     <b>frombuffer(mode, size, data, "raw", mode, 0, 1)</b>.
  1830. # @return An Image object.
  1831. # @since 1.1.4
  1832.  
  1833. def frombuffer(mode, size, data, decoder_name="raw", *args):
  1834.     "Load image from string or buffer"
  1835.  
  1836.     # may pass tuple instead of argument list
  1837.     if len(args) == 1 and isTupleType(args[0]):
  1838.         args = args[0]
  1839.  
  1840.     if decoder_name == "raw":
  1841.         if args == ():
  1842.             if warnings:
  1843.                 warnings.warn(
  1844.                     "the frombuffer defaults may change in a future release; "
  1845.                     "for portability, change the call to read:\n"
  1846.                     "  frombuffer(mode, size, data, 'raw', mode, 0, 1)",
  1847.                     RuntimeWarning, stacklevel=2
  1848.                 )
  1849.             args = mode, 0, -1 # may change to (mode, 0, 1) post-1.1.6
  1850.         if args[0] in _MAPMODES:
  1851.             im = new(mode, (1,1))
  1852.             im = im._new(
  1853.                 core.map_buffer(data, size, decoder_name, None, 0, args)
  1854.                 )
  1855.             im.readonly = 1
  1856.             return im
  1857.  
  1858.     return fromstring(mode, size, data, decoder_name, args)
  1859.  
  1860.  
  1861. ##
  1862. # (New in 1.1.6) Creates an image memory from an object exporting
  1863. # the array interface (using the buffer protocol).
  1864. #
  1865. # If obj is not contiguous, then the tostring method is called
  1866. # and {@link frombuffer} is used.
  1867. #
  1868. # @param obj Object with array interface
  1869. # @param mode Mode to use (will be determined from type if None)
  1870. # @return An image memory.
  1871.  
  1872. def fromarray(obj, mode=None):
  1873.     arr = obj.__array_interface__
  1874.     shape = arr['shape']
  1875.     ndim = len(shape)
  1876.     try:
  1877.         strides = arr['strides']
  1878.     except KeyError:
  1879.         strides = None
  1880.     if mode is None:
  1881.         try:
  1882.             typekey = (1, 1) + shape[2:], arr['typestr']
  1883.             mode, rawmode = _fromarray_typemap[typekey]
  1884.         except KeyError:
  1885.             # print typekey
  1886.             raise TypeError("Cannot handle this data type")
  1887.     else:
  1888.         rawmode = mode
  1889.     if mode in ["1", "L", "I", "P", "F"]:
  1890.         ndmax = 2
  1891.     elif mode == "RGB":
  1892.         ndmax = 3
  1893.     else:
  1894.         ndmax = 4
  1895.     if ndim > ndmax:
  1896.         raise ValueError("Too many dimensions.")
  1897.  
  1898.     size = shape[1], shape[0]
  1899.     if strides is not None:
  1900.         obj = obj.tostring()
  1901.  
  1902.     return frombuffer(mode, size, obj, "raw", rawmode, 0, 1)
  1903.  
  1904. _fromarray_typemap = {
  1905.     # (shape, typestr) => mode, rawmode
  1906.     # first two members of shape are set to one
  1907.     # ((1, 1), "|b1"): ("1", "1"), # broken
  1908.     ((1, 1), "|u1"): ("L", "L"),
  1909.     ((1, 1), "|i1"): ("I", "I;8"),
  1910.     ((1, 1), "<i2"): ("I", "I;16"),
  1911.     ((1, 1), ">i2"): ("I", "I;16B"),
  1912.     ((1, 1), "<i4"): ("I", "I;32"),
  1913.     ((1, 1), ">i4"): ("I", "I;32B"),
  1914.     ((1, 1), "<f4"): ("F", "F;32F"),
  1915.     ((1, 1), ">f4"): ("F", "F;32BF"),
  1916.     ((1, 1), "<f8"): ("F", "F;64F"),
  1917.     ((1, 1), ">f8"): ("F", "F;64BF"),
  1918.     ((1, 1, 3), "|u1"): ("RGB", "RGB"),
  1919.     ((1, 1, 4), "|u1"): ("RGBA", "RGBA"),
  1920.     }
  1921.  
  1922. # shortcuts
  1923. _fromarray_typemap[((1, 1), _ENDIAN + "i4")] = ("I", "I")
  1924. _fromarray_typemap[((1, 1), _ENDIAN + "f4")] = ("F", "F")
  1925.  
  1926. ##
  1927. # Opens and identifies the given image file.
  1928. # <p>
  1929. # This is a lazy operation; this function identifies the file, but the
  1930. # actual image data is not read from the file until you try to process
  1931. # the data (or call the {@link #Image.load} method).
  1932. #
  1933. # @def open(file, mode="r")
  1934. # @param file A filename (string) or a file object.  The file object
  1935. #    must implement <b>read</b>, <b>seek</b>, and <b>tell</b> methods,
  1936. #    and be opened in binary mode.
  1937. # @param mode The mode.  If given, this argument must be "r".
  1938. # @return An Image object.
  1939. # @exception IOError If the file cannot be found, or the image cannot be
  1940. #    opened and identified.
  1941. # @see #new
  1942.  
  1943. def open(fp, mode="r"):
  1944.     "Open an image file, without loading the raster data"
  1945.  
  1946.     if mode != "r":
  1947.         raise ValueError("bad mode")
  1948.  
  1949.     if isStringType(fp):
  1950.         import __builtin__
  1951.         filename = fp
  1952.         fp = __builtin__.open(fp, "rb")
  1953.     else:
  1954.         filename = ""
  1955.  
  1956.     prefix = fp.read(16)
  1957.  
  1958.     preinit()
  1959.  
  1960.     for i in ID:
  1961.         try:
  1962.             factory, accept = OPEN[i]
  1963.             if not accept or accept(prefix):
  1964.                 fp.seek(0)
  1965.                 return factory(fp, filename)
  1966.         except (SyntaxError, IndexError, TypeError):
  1967.             pass
  1968.  
  1969.     if init():
  1970.  
  1971.         for i in ID:
  1972.             try:
  1973.                 factory, accept = OPEN[i]
  1974.                 if not accept or accept(prefix):
  1975.                     fp.seek(0)
  1976.                     return factory(fp, filename)
  1977.             except (SyntaxError, IndexError, TypeError):
  1978.                 pass
  1979.  
  1980.     raise IOError("cannot identify image file")
  1981.  
  1982. #
  1983. # Image processing.
  1984.  
  1985. ##
  1986. # Creates a new image by interpolating between two input images, using
  1987. # a constant alpha.
  1988. #
  1989. # <pre>
  1990. #    out = image1 * (1.0 - alpha) + image2 * alpha
  1991. # </pre>
  1992. #
  1993. # @param im1 The first image.
  1994. # @param im2 The second image.  Must have the same mode and size as
  1995. #    the first image.
  1996. # @param alpha The interpolation alpha factor.  If alpha is 0.0, a
  1997. #    copy of the first image is returned. If alpha is 1.0, a copy of
  1998. #    the second image is returned. There are no restrictions on the
  1999. #    alpha value. If necessary, the result is clipped to fit into
  2000. #    the allowed output range.
  2001. # @return An Image object.
  2002.  
  2003. def blend(im1, im2, alpha):
  2004.     "Interpolate between images."
  2005.  
  2006.     im1.load()
  2007.     im2.load()
  2008.     return im1._new(core.blend(im1.im, im2.im, alpha))
  2009.  
  2010. ##
  2011. # Creates a new image by interpolating between two input images,
  2012. # using the mask as alpha.
  2013. #
  2014. # @param image1 The first image.
  2015. # @param image2 The second image.  Must have the same mode and
  2016. #    size as the first image.
  2017. # @param mask A mask image.  This image can can have mode
  2018. #    "1", "L", or "RGBA", and must have the same size as the
  2019. #    other two images.
  2020.  
  2021. def composite(image1, image2, mask):
  2022.     "Create composite image by blending images using a transparency mask"
  2023.  
  2024.     image = image2.copy()
  2025.     image.paste(image1, None, mask)
  2026.     return image
  2027.  
  2028. ##
  2029. # Applies the function (which should take one argument) to each pixel
  2030. # in the given image. If the image has more than one band, the same
  2031. # function is applied to each band. Note that the function is
  2032. # evaluated once for each possible pixel value, so you cannot use
  2033. # random components or other generators.
  2034. #
  2035. # @def eval(image, function)
  2036. # @param image The input image.
  2037. # @param function A function object, taking one integer argument.
  2038. # @return An Image object.
  2039.  
  2040. def eval(image, *args):
  2041.     "Evaluate image expression"
  2042.  
  2043.     return image.point(args[0])
  2044.  
  2045. ##
  2046. # Creates a new image from a number of single-band images.
  2047. #
  2048. # @param mode The mode to use for the output image.
  2049. # @param bands A sequence containing one single-band image for
  2050. #     each band in the output image.  All bands must have the
  2051. #     same size.
  2052. # @return An Image object.
  2053.  
  2054. def merge(mode, bands):
  2055.     "Merge a set of single band images into a new multiband image."
  2056.  
  2057.     if getmodebands(mode) != len(bands) or "*" in mode:
  2058.         raise ValueError("wrong number of bands")
  2059.     for im in bands[1:]:
  2060.         if im.mode != getmodetype(mode):
  2061.             raise ValueError("mode mismatch")
  2062.         if im.size != bands[0].size:
  2063.             raise ValueError("size mismatch")
  2064.     im = core.new(mode, bands[0].size)
  2065.     for i in range(getmodebands(mode)):
  2066.         bands[i].load()
  2067.         im.putband(bands[i].im, i)
  2068.     return bands[0]._new(im)
  2069.  
  2070. # --------------------------------------------------------------------
  2071. # Plugin registry
  2072.  
  2073. ##
  2074. # Register an image file plugin.  This function should not be used
  2075. # in application code.
  2076. #
  2077. # @param id An image format identifier.
  2078. # @param factory An image file factory method.
  2079. # @param accept An optional function that can be used to quickly
  2080. #    reject images having another format.
  2081.  
  2082. def register_open(id, factory, accept=None):
  2083.     id = string.upper(id)
  2084.     ID.append(id)
  2085.     OPEN[id] = factory, accept
  2086.  
  2087. ##
  2088. # Registers an image MIME type.  This function should not be used
  2089. # in application code.
  2090. #
  2091. # @param id An image format identifier.
  2092. # @param mimetype The image MIME type for this format.
  2093.  
  2094. def register_mime(id, mimetype):
  2095.     MIME[string.upper(id)] = mimetype
  2096.  
  2097. ##
  2098. # Registers an image save function.  This function should not be
  2099. # used in application code.
  2100. #
  2101. # @param id An image format identifier.
  2102. # @param driver A function to save images in this format.
  2103.  
  2104. def register_save(id, driver):
  2105.     SAVE[string.upper(id)] = driver
  2106.  
  2107. ##
  2108. # Registers an image extension.  This function should not be
  2109. # used in application code.
  2110. #
  2111. # @param id An image format identifier.
  2112. # @param extension An extension used for this format.
  2113.  
  2114. def register_extension(id, extension):
  2115.     EXTENSION[string.lower(extension)] = string.upper(id)
  2116.  
  2117.  
  2118. # --------------------------------------------------------------------
  2119. # Simple display support.  User code may override this.
  2120.  
  2121. def _show(image, **options):
  2122.     # override me, as necessary
  2123.     apply(_showxv, (image,), options)
  2124.  
  2125. def _showxv(image, title=None, **options):
  2126.     import ImageShow
  2127.     apply(ImageShow.show, (image, title), options)
  2128.